import sys
import pygame

from settings import Settings
from ship import Ship

class AlienInvasion:
	"""管理游戏资源和行为的类"""
	def __init__(self):
		pygame.init()
		self.settings = Settings()
		self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
		self.settings.screen_width = self.screen.get_rect().width
		self.settings.screen_height = self.screen.get_rect().height
		pygame.display.set_caption("Alien Invasion")
		self.ship = Ship(self)

		print("外星人游戏已启动...")

	def run_game(self):
		"""开始游戏的主循环"""
		while True:
			self.check_events()
			self.ship.update()
			self.update_screen()

	def check_events(self):
		# 监听键盘和鼠标事件
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				sys.exit()
			elif event.type == pygame.KEYDOWN:
				self.check_keydown_events(event)
			elif event.type == pygame.KEYUP:
				self.check_keyup_events(event)

	def check_keydown_events(self, event):
		if event.key == pygame.K_RIGHT:
			self.ship.moving_right = True
		elif event.key == pygame.K_LEFT:
			self.ship.moving_left = True
		elif event.key == pygame.K_UP:
			self.ship.moving_up = True
		elif event.key == pygame.K_DOWN:
			self.ship.moving_down = True
		elif event.key == pygame.K_ESCAPE:
			sys.exit()

	def check_keyup_events(self, event):
		if event.key == pygame.K_RIGHT:
			self.ship.moving_right = False
		elif event.key == pygame.K_LEFT:
			self.ship.moving_left = False
		elif event.key == pygame.K_UP:
			self.ship.moving_up = False
		elif event.key == pygame.K_DOWN:
			self.ship.moving_down = False

	def update_screen(self):
		# 屏幕背景色 
		self.screen.fill(self.settings.bg_color)

		# 显示飞船
		self.ship.blit_me()

	    # 让最近绘制的屏幕可见
		pygame.display.flip()


if __name__ == '__main__':
	alien_invasion = AlienInvasion()
	alien_invasion.run_game()